package org.hhy.xxl.crud.config;

import com.google.common.collect.Lists;
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 *
 * @author LiuHao
 * @date 2020/9/23 10:13
 * @description es配置
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "cloud.elasticsearch")
public class ElasticSearchConfig {

    /**
     * 协议 http
     */
    private String schema;

    /**
     * 服务地址，集群使用','隔开
     */
    private String address;
    /**
     * 连接超时时间
     */
    private Integer connectTimeout;
    /**
     * Socket连接超时时间
     */
    private Integer socketTimeout;
    /**
     * 连接请求超时时间
     */
    private Integer connectionRequestTimeout;
    /**
     * 最大连接数
     */
    private Integer maxCountNum;
    /**
     * 最大连接路由数
     */
    private Integer maxConnectPerRoute;


    @Bean
    public RestHighLevelClient restHighLevelClient(){

        //拆分地址
        List<HttpHost> hosts = Lists.newArrayList();
        for(String addr : address.split(",")){
            String[] host_port = addr.split(":");
            hosts.add(new HttpHost(host_port[0],Integer.valueOf(host_port[1]),schema));
        }
        //构建连接对象

        RestClientBuilder builder = RestClient.builder(hosts.toArray(new HttpHost[]{}));
        //异步连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder->{
           requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);
           requestConfigBuilder.setConnectTimeout(connectTimeout);
           requestConfigBuilder.setSocketTimeout(socketTimeout);
           return requestConfigBuilder;
        });
        //异步连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder->{
           httpClientBuilder.setMaxConnTotal(maxCountNum);
           httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
           return httpClientBuilder;
        });
        return new RestHighLevelClient(builder);
    }


}
